<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="goodsPage.key"
        placeholder="搜索"
        style="width: 300px"
        class="filter-item"
        :clearable="true"
        @keyup.enter.native="handleGoodsFilter"
      />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleGoodsFilter">
        查询
      </el-button>
      <el-button-group class="filter-item">
        <el-button plain>全部</el-button>
        <el-button plain>上架</el-button>
        <el-button plain>下架</el-button>
      </el-button-group>
      <el-button class="filter-item" style="margin-left: 10px" type="primary" icon="el-icon-edit" @click="handleGoodsAdd">
        新增
      </el-button>
      <el-button :loading="downloadGoodsBtnLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleGoodsExport">
        导出
      </el-button>
    </div>

    <!-- 表格组件 -->
    <el-table v-loading="goodsTableLoading" :data="goodsTableData" style="width: 100%">
      <el-table-column prop="title" label="标题" width="180" />
      <el-table-column prop="categoryName" label="商品分类" />
      <el-table-column prop="brandName" label="品牌名称" />
      <el-table-column prop="saleable" label="是否上架" />
      <el-table-column prop="valid" label="是否有效" />
      <el-table-column fixed="right" label="操作" width="150">
        <template slot-scope="scope">
          <el-button :loading="editGoodsBtnLoading" type="warning" icon="el-icon-edit" @click="handleGoodsEdit(scope.row)" />
          <el-button :loading="deleteGoodsBtnLoading" type="danger" icon="el-icon-delete" @click="handleGoodsDelete(scope.row)" />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      layout="total, sizes, prev, pager, next, jumper"
      :page-size="goodsPage.pageSize"
      :page-count="goodsPage.totalPages"
      ::page-sizes="goodsPage.pageSegments"
      :total="goodsPage.totalCount"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="goodsDialogEdit ? '编辑商品': '新增商品'"
      :visible.sync="goodsDialogVisible"
      @open="handleGoodsDialogOpen"
      @opened="handleGoodsDialogOpened"
      @closed="handleGoodsDialogClosed"
    >
      <!-- 商品编辑组件 -->
      <goods-form :is-edit="goodsDialogEdit" :old-goods="oldGoods" @goodsDialogClose="handleGoodsDialogClose" />
    </el-dialog>
  </div>
</template>
<script>
import goodsForm from './goodsForm.vue'

import { listSpuByPage, getSpuDetail, deleteSpu, listSku } from '@/api/goods'

export default {
  components: { goodsForm },
  data() {
    const validateGoodsName = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入品牌名称'))
      } else {
        callback()
      }
    }

    return {
      downloadGoodsBtnLoading: false,

      editGoodsBtnLoading: false,
      deleteGoodsBtnLoading: false,

      goodsTableLoading: false,
      goodsTableData: [],

      goodsPage: {
        key: '',
        saleable: '',
        currentPage: 0,
        pageSize: 10,
        pageSegments: [],
        totalPages: 0,
        totalCount: 0
      },

      goodsRules: {
        goodsName: [{ required: true, trigger: 'blur', validator: validateGoodsName }]
      },

      goodsDialogVisible: false,
      goodsDialogEdit: false,

      oldGoods: {
        spuDetail: {},
        skus: []
      }
    }
  },
  watch: {
    goodsPage: {
      deep: true,
      handler(goodsPage) {
        this.listGoods(goodsPage)
      }
    }
  },
  mounted() {
    this.listGoods(this.goodsPage)
  },
  methods: {
    /**
     * 分页查询品牌
     */
    listGoods(params) {
      this.brandTableLoading = true

      listSpuByPage(params)
        .then((res) => {
          if (!res) {
            this.goodsTableData = []
            return
          }

          this.goodsPage.currentPage = parseInt(res.currentPage)
          this.goodsPage.pageSegments = parseInt(res.pageSegments)
          this.goodsPage.pageSize = parseInt(res.pageSize)
          this.goodsPage.totalPages = parseInt(res.totalPages)
          this.goodsPage.totalCount = parseInt(res.totalCount)

          if (res.rows) {
            this.goodsTableData = res.rows
          } else {
            this.goodsTableData = []
          }
        })
        .catch(err => {
          console.log(err)
        })
        .then(() => {
          this.goodsTableLoading = false
        })
    },

    /**
     * 条件查询
     */
    handleGoodsFilter() {
      // 查询商品
      this.listGoods(this.goodsPage)
    },

    /**
     * 新增
     */
    handleGoodsAdd() {
      this.goodsDialogEdit = false
      this.goodsDialogVisible = true
      this.oldGoods = {}
    },

    /**
     * 导出
     */
    handleGoodsExport() {
      this.downloadGoodsBtnLoading = true
      import('@/vendor/Export2Excel').then((excel) => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['', '', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadGoodsBtnLoading = false
      })
    },

    /**
     * 处理编辑商品
     */
    async handleGoodsEdit(oldGoods) {
      // 同步查询spuDetail
      const spuDetail = await getSpuDetail(oldGoods.id)
      oldGoods.spuDetail = spuDetail

      // 同步查询sku集合
      const skus = await listSku(oldGoods.id)
      oldGoods.skus = skus

      this.goodsDialogEdit = true
      this.goodsDialogVisible = true

      this.oldGoods = oldGoods
    },

    /**
     * 处理删除商品
     */
    handleGoodsDelete(row) {
      this.deleteGoodsBtnLoading = true
      this.$confirm('确定要删除改商品吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteSpu(row.id)
          .then(res => {
          })
          .catch(err => {
            this.$message.error('删除商品失败！' + err)
          })
          .then(() => {
            // 查询商品
            this.listGoods(this.goodsPage)

            this.$message({ type: 'success', message: '删除成功!' })
          })
      }).catch(() => {
      }).then(() => {
        this.deleteGoodsBtnLoading = false
      })
    },

    /**
     * 翻页
     */
    handleCurrentChange(currentPage) {
      // 查询品牌
      const params = {
        key: this.key,
        currentPage
      }
      this.listGoods(params)
    },

    /**
     * 修改每页数据量
     */
    handleSizeChange(pageSize) {
      const params = {
        key: this.key,
        currentPage: this.brandPage.currentPage,
        pageSize
      }
      this.listGoods(params)
    },

    /**
     * 重置品牌表单
     */
    resetGoodsForm() {
    },

    /**
     * 处理子组件发送的关闭对话框事件
     */
    handleGoodsDialogClose() {
      this.goodsDialogVisible = false
    },

    /**
     * 商品对话框打开前回调
     */
    handleGoodsDialogOpen() {
    },

    /**
     * 商品对话框打开后回调
     */
    handleGoodsDialogOpened() {
    },

    /**
     * 商品对话框关闭后回调
     */
    handleGoodsDialogClosed() {
    }
  }
}
</script>
<style scoped>
</style>
